<template>
  <div class="layout" id="applyWrapper">
    <div class="applyBox">
      <div style="display: flex; justify-content: space-between">
        <Breadcrumb class="breadcrumb" :crumbs="crumbs"></Breadcrumb>
        <Buttons :buttons="btn" @goBack="goBack"></Buttons>
      </div>
      <div class="contain">
        <div class="tile">金融诉求申请</div>
        <div class="box">
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            label-width="120px"
            style="text-align: left"
          >
            <div class="titleDiv">诉求基本信息</div>
            <el-form-item label="诉求名称：" prop="title">
              <el-input
                placeholder="请输入诉求名称"
                v-model.trim="form.title"
                maxlength="20"
                class="input-div"
              ></el-input>
              <span style="font-size: 14px; color: #999; margin-left: 10px"
                >输入字符不超过20个字符</span
              >
            </el-form-item>
            <el-form-item label="联系人：" prop="contacts">
              <el-input
                placeholder="请输入联系人"
                :maxlength="10"
                v-model.trim="form.contacts"
                class="input-div"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="联系电话：" prop="contactNumber">
              <el-input
                placeholder="请输入联系电话"
                maxlength="13"
                v-model.trim="form.contactNumber"
                class="input-div">
              </el-input>
            </el-form-item>
            <el-form-item label="金融类型：" prop="experience">
              <el-select
                placeholder="请选择"
                v-model.trim="form.experience"
                @change="changeExperience"
                style="width: 360px"
              >
                <el-option
                  v-for="experienceOption in experienceOptions"
                  :key="experienceOption.dictValue"
                  :label="experienceOption.dictLabel"
                  :value="experienceOption.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
            <div v-if="!financeShow">
              <div class="titleDiv">诉求原因</div>
              <el-form-item label="诉求原因：" prop="appealReason">
                <el-input
                  placeholder="请输入诉求原因"
                  type="textarea"
                  resize="none"
                  :maxlength="300"
                  :autosize="{ minRows: 4, maxRows: 4 }"
                  v-model.trim="form.appealReason"
                  :show-word-limit="true"
                ></el-input>
              </el-form-item>
              <!-- <el-form-item label="诉求文件上传：">
              <div style="text-align: left">
                <el-button class="uploadBtn" icon="el-icon-upload" @click="selectFile()">上传文件</el-button>
                <div style="display: flex; align-items: center" v-for="(file, index) in sendMsg.files" :key="index">
                  <span>{{file.name}}</span>
                  <i class="el-icon-close deleteBtn" @click="deleteFile(index)"></i>
                </div>
                <input type="file" ref="fileInput" accept=".rar,.zip,.dox,.docx,.pdf,.jpg" v-show="false" @change="changeFile"></input>
                <div style="color: #999999">支持扩展名：.rar .zip .dox .docx .pdf .jpg</div>
              </div>
            </el-form-item> -->
              <el-form-item label="诉求文件上传：" prop="appealFile">
                <addUpload @changeUp="changeUp"></addUpload>
              </el-form-item>
            </div>
            <!-- 金融类型 -->
            <div class="finance-div" v-if="financeShow">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="融资名称" prop="financeName">
                    <el-input
                      ref="financeName"
                      v-model.trim="form.financeName"
                      :maxlength="30"
                      placeholder="请输入"
                      style="width:240px"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="融资期限" prop="financeTerm">
                    <el-date-picker
                      v-model.trim="form.financeTerm"
                      :picker-options="pickerOptions"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="yyyy-MM-dd"
                      style="width:240px">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="融资类型" prop="financeType">
                    <el-select v-model.trim="form.financeType" placeholder="请选择" style="width:240px">
                      <el-option
                        v-for="typeItem in financeTypeOptions"
                        :key="typeItem.dictValue"
                        :label="typeItem.dictLabel"
                        :value="typeItem.dictValue"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="融资金额" prop="financeMoney">
                    <el-input
                      v-model.trim="form.financeMoney"
                      maxlength="10"
                      placeholder="请输入"
                      style="width:240px">
                      <div slot="append">万元</div>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="简介" prop="financeBrief">
                    <!-- <el-input
                      v-model.trim="form.financeBrief"
                      placeholder="请输入"
                      style="width:240px"
                      type="textarea"
                      maxlength="300"
                    ></el-input> -->
                    <el-input
                      type="textarea"
                      v-model.trim="form.financeBrief"
                      resize="none"
                      maxlength="300"
                      :rows="4"
                      class="reason-input"
                      placeholder="请输入"
                      style="width:240px !important;"
                      :show-word-limit="true"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="资金用途" prop="financeFunds">
                    <!-- <el-input
                      v-model.trim="form.financeFunds"
                      placeholder="请输入"
                      maxlength="100"
                      style="width:200px"
                    ></el-input> -->
                    <el-input
                      type="textarea"
                      v-model.trim="form.financeFunds"
                      resize="none"
                      maxlength="100"
                      :rows="4"
                      class="reason-input"
                      placeholder="请输入"
                      style="width:240px !important;"
                      :show-word-limit="true"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="融资轮次" prop="financeRound">
                    <el-select v-model.trim="form.financeRound" placeholder="请选择" style="width:240px">
                      <el-option
                        v-for="roundItem in financeRoundOptions"
                        :key="roundItem.dictValue"
                        :label="roundItem.dictLabel"
                        :value="roundItem.dictValue"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">  
                  <el-form-item label="担保方式" prop="financeGurantee">
                    <el-select
                      v-model.trim="form.financeGurantee"
                      placeholder="请选择"
                      style="width:240px">
                      <el-option
                        v-for="statusItem in financeGuaranteeOptions"
                        :key="statusItem.dictValue"
                        :label="statusItem.dictLabel"
                        :value="statusItem.dictValue"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="公司财务状况" prop="financeStatus">
                    <el-select
                      v-model.trim="form.financeStatus"
                      placeholder="请选择"
                      style="width:240px">
                      <el-option
                        v-for="statusItem in financeStatusOptions"
                        :key="statusItem.dictValue"
                        :label="statusItem.dictLabel"
                        :value="statusItem.dictValue"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="融资期望" prop="financeExpect">
                    <el-input
                      v-model.trim="form.financeExpect"
                      placeholder="请输入" 
                      style="width:240px"
                      maxlength="30"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="企业标签：" prop="financeLabel">
                    <div class="promptspan">输入标签自定义最多5个(标签长度不能超10)</div>
                    <el-select
                      v-model="form.financeLabel"
                      multiple
                      filterable
                      allow-create
                      default-first-option
                      :multiple-limit="5"
                      placeholder="请输入企业标签"
                      style="width:240px">
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <!-- <el-form-item label="企业标签" prop="financeLabel">
                    <el-input
                      v-model.trim="form.financeLabel"
                      placeholder="请输入"
                      style="width:200px"
                    ></el-input>
                  </el-form-item> -->
                </el-col>
                <el-col :span="12">
                  <el-form-item label="公司官网">
                    <el-input
                      v-model.trim="form.areaValue"
                      placeholder="请输入"
                      style="width:240px"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="项目描述：">
                <el-select
                  style="margin-right: 300px;width:240px;"
                  v-model.trim="form.describeType"
                  placeholder="请选择">
                  <el-option 
                    v-for="(item, index) in financeDescribeOptions" 
                    :key="index" 
                    :label="item.dictLabel" 
                    :value="item.dictValue">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="">
                <el-input
                  type="textarea"
                  v-model.trim="form.financeDescribe"
                  resize="none"
                  maxlength="500"
                  :rows="4"
                  class="reason-input"
                  placeholder="请输入详细描述"
                  style="width:500px"
                  :show-word-limit="true"
                ></el-input>
              </el-form-item>

              <el-form-item label="项目详情" prop="projectDetails">
                <editor
                  v-model.trim="form.projectDetails"
                  :min-height="192"
                  @on-change="handleTextChange"
                />
              </el-form-item>
            </div>
            <Buttons :buttons="buttons" @goBack="goBack" @save="submitForm('form')" @apply="submitForm('form', 1)" class="btns"></Buttons>
            <!-- <el-form-item label="">
              <div style="text-align: center">
                <div class="sendBtn2" @click="goBack()">取消</div>
                <div class="sendBtn" @click="submitForm('form')">保存</div>
                <div class="sendBtn" @click="submitForm('form', 1)">申请</div>
              </div>
            </el-form-item> -->
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Breadcrumb from "@/components/breadcrumb";
import addUpload from "@/components/financiaUpload";
import Editor from "@/components/Editor";
import { formatSendBtn } from "@/utils/util.js";
import { host } from "@/utils/config.js";
import { request } from "@/utils/request.js";

import financingApplyRules from '@/formRules/financial/financingApplyRules.js'

export default {
  mixins: [financingApplyRules],
  data() {
    return {
      buttons:[
        {text:"取消",type:"normal",size:"l",method:"goBack"},
        {text:"保存",type:"success",size:"l",method:"save"},
        {text:"申请",type:"success",size:"l",method:"apply"}
      ],
      btn:[
        {text:"返回上一步",type:"normal",size:"s",method:"goBack"},
      ],
      crumbs: [
        {
          label: "金融服务",
          value: "finance"
        },
        {
          label: "金融诉求申请",
          value: "",
          choose: true
        }
      ],
      sendMsg: {
        policyId: null,
        reason: "",
        files: []
      },
      options: [],
      financeShow: false, // 是否展示金融诉求相关
      experienceOptions: [], // 金融类型
      financeTypeOptions: [], // 融资类型
      financeRoundOptions: [], // 融资轮次
      financeStatusOptions: [], // 公司财务状况
      financeGuaranteeOptions: [], // 担保方式
      financeDescribeOptions: [], // 项目描述类型	
      descriptionText: null,
      pickerOptions: {
        disabledDate: (time) => time.getTime() < Date.now() - 8.64e7
      }
    };
  },
  components: {
    Breadcrumb,
    addUpload,
    Editor
  },
  mounted() {
    this.getFinanceTypeList();
  },
  methods: {
    async getFinanceTypeList() {
      let api = `finance_appeal_type,finance_financing_type,finance_financing_turn,finance_com_finance_status,finance_guarantee_way,finance_describe_type`;
      // 调用公共方法中的查询字典表
      this.getDictList(this, api).then((res) => {
        // 金融类型
        this.experienceOptions = res.finance_appeal_type;
        // 融资类型
        this.financeTypeOptions = res.finance_financing_type;
        // 融资轮次
        this.financeRoundOptions = res.finance_financing_turn;
        // 公司财务状况
        this.financeStatusOptions = res.finance_com_finance_status;
        // 担保方式	
        this.financeGuaranteeOptions = res.finance_guarantee_way;
        // 项目描述类型	 
        this.financeDescribeOptions = res.finance_describe_type;
      })
    },
    /**
     * 富文本触发
     * @param obj 上传文件数据
     * @return {void}
     */
    handleTextChange(obj) {
      const { html, text, quill } = obj;
      let value = quill.getText();
      let trimLength = value.trim().length;
      if (value.length > trimLength) {
        quill.deleteText(trimLength, value.length);
      }
      this.descriptionText = quill.getText().trim();
    },
    /**
     * 上传文件触发
     * @param obj 上传文件数据
     * @return {void}
     */
    changeUp(obj) {
      // let arr = [];
      // for (let i in obj) {
      //   arr.push(obj[i].batchId);
      // }
      // this.form.appealFile = arr.join(",");
      this.form.appealFile = obj[0].batchId
      this.$refs["form"].validateField("appealFile");
    },
    changeExperience() {
      if (this.form.experience == "1") {
        this.financeShow = true;
        document.getElementById("applyWrapper").scrollTop = "100px";
        // console.log('this.$refs', this.$refs)
        setTimeout(() => {
          this.$refs['financeName'].focus()  
        }, 500);
      } else {
        this.financeShow = false;
      }
    },
    submitForm(formName, type) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // console.log(12345, this.form);
          // console.log(23333, this.form.financeTerm[0]);
          // console.log(23333, new Date(this.form.financeTerm[1]));
          let stateNum = "";
          if (type == 1) {
            stateNum = 1;
          }
          if (this.form.experience == "1") {
            let dataObj1 = {
              appealName: this.form.title,
              contacts: this.form.contacts,
              contactsTel: this.form.contactNumber,
              financingName: this.form.financeName,
              financingType: this.form.financeType,
              financingTurn: this.form.financeRound,
              financeStatus: this.form.financeStatus,
              describeType: this.form.describeType,
              projectDescribe: this.form.financeDescribe,
              projectDetails: this.form.projectDetails,
              startTimeStr: this.form.financeTerm[0],
              endTimeStr: this.form.financeTerm[1],
              financingMoney: this.form.financeMoney,
              financingPurpose: this.form.financeFunds,
              guaranteeType: this.form.financeGurantee,
              financingExpect: this.form.financeExpect,
              officialWebsite: this.form.areaValue,
              companyTag: this.form.financeLabel.join(','),
              financingStatus: type==1? 1: 0,
              financingIntroduce: this.form.financeBrief
            };
            console.log('dataObj1', dataObj1)
            this.subFinance(dataObj1,type);
          } else {
            let dataObj = {
              title: this.form.title,
              contacts: this.form.contacts,
              contactNumber: this.form.contactNumber,
              financeType: this.form.experience,
              appealReason: this.form.appealReason,
              fileBatchId: this.form.appealFile,
              state: stateNum
            };
            this.subAppeal(dataObj,type);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    /**
     * 企业诉求触发
     * @param {void}
     * @return {void}
     */
    subAppeal(obj,type) {
      let text = ''
      if(type == 1){
        text  = '您确定做此次操作，申请之后将进入下一阶段，并无法取消?'
      } else {
        text  = '您确定做此次操作，保存本次数据,,不申请?'
      }
      this.$confirm(text, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.getAppeal(obj,type)
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
    },
    async getAppeal(obj,type){
      let api = `${host}/finance/company/other/appeal/add`;
      let res = await request(this, api, obj, "POST");
      if (res.code == 200) {
        // this.$message.success("申请成功");
        this.$message.success(`${type == 1? '申请成功' :'保存成功'}`);
        this.$router.back();
      } else {
        this.$message.error(res.msg);
      }
    },
    /**
     * 金融诉求触发
     * @param {void}
     * @return {void}
     */
    subFinance(obj,type) {
      let text = ''
      if(type == 1){
        text  = '您确定做此次操作，申请之后将进入下一阶段，并无法取消?'
      } else {
        text  = '您确定做此次操作，保存本次数据,,不申请?'
      }
      this.$confirm(text, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.getAddFinancing(obj,type)
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
     
    },
    async getAddFinancing(obj,type){
      let api = `${host}/finance/companyFinancing/addFinancing`;
      let res = await request(this, api, obj, "POST");
      if (res.code == 200) {
        this.$message.success(`${type == 1? '申请成功' :'保存成功'}`);
        this.$router.back();
      } else {
        this.$message.error(res.msg);
      }
    },
    /**
     * 返回上一页
     */
    goBack() {
      this.$confirm('你是否需要放弃本次操作，取消将无法保存数据', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$router.back();
          this.$refs['form'].resetFields()
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
      
    },
    /**
     * 选择文件事件
     */
    selectFile() {
      let ns = this;
      ns.$refs.fileInput.click();
    },
    /**
     * 完成选择文件事件
     */
    changeFile: function(e) {
      let ns = this;
      let file = e.target.files[0];
      if (file == undefined) {
        return;
      }
      if (file.size / 1048576 >= 50) {
        ns.$message.error("文件大小不能超过50MB");
        return;
      }
      if (
        !confirmEnding(file.name, [
          ".rar",
          ".zip",
          ".dox",
          ".docx",
          ".pdf",
          ".jpg"
        ])
      ) {
        ns.$message.error("文件格式不正确");
        return;
      }
      ns.sendMsg.files.push(file);
    },
    /**
     * 删除文件
     */
    deleteFile(index) {
      let ns = this;
      let fileList = [];
      for (let i = 0; i < ns.sendMsg.files.length; i++) {
        if (i != index) {
          fileList.push(ns.sendMsg.files[i]);
        }
      }
      ns.sendMsg.files = fileList;
    },
    /**
     * 格式化显示按钮颜色
     */
    formatBtn(policy) {
      return formatSendBtn(policy);
    }
  }
};
</script>
<style scoped>
.promptspan {
  font-size: 12px;
  color: #bbbbbb;
  position: absolute;
  top: -30px;
  left: 0;
}
.applyBox {
  width: 1000px;
  margin: 0 auto;
  padding: 20px 0;
}
.breadcrumb {
  width: 1000px;
  margin-bottom: 30px;
}
.applyBox .backBtn {
  border: 1px solid #eeeeee;
  white-space: nowrap;
  font-size: 12px;
  height: 30px;
  width: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 3px;
  cursor: pointer;
}
.applyBox .contain {
  width: 750px;
  margin: 0 auto;
}
.applyBox .contain .tile {
  height: 46px;
  border-bottom: 2px solid #045db9;
  font-size: 24px;
  font-weight: 700;
  color: #333333;
}
.applyBox .contain .box .titleDiv {
  height: 40px;
  background: #f1f2f4;
  margin-top: 24px;
  line-height: 40px;
  box-sizing: border-box;
  padding-left: 20px;
  font-size: 14px;
  font-weight: bold;
  color: #333333;
  text-align: left;
}
::v-deep .applyBox .el-form-item {
  margin-top: 20px;
}
.applyBox .contain .box .deleteBtn {
  font-size: 20px;
  color: #d00000;
  font-weight: bold;
  margin-left: 10px;
}
.applyBox .contain .box .sendBtn {
  padding: 0 40px;
  background-color: #045db9;
  display: inline-block;
  color: #ffffff;
  border-radius: 5px;
  transition: all 0.2s ease 0s;
  margin-right: 10px;
}

.applyBox .contain .box .sendBtn:hover {
  box-shadow: 0px 5px 5px #e1e1e1;
  cursor: pointer;
}
.applyBox .contain .box .sendBtn2 {
  padding: 0 40px;
  background-color: #ffffff;
  display: inline-block;
  border-radius: 5px;
  transition: all 0.2s ease 0s;
  margin-right: 10px;
  border: 1px solid #eeeeee;
  color: #333333;
  cursor: pointer;
}
.input-div {
  width: 360px !important;
}
.el-textarea {
  width: 100% !important;
}
.btns{
  margin: 20px 0;
}
</style>
